
from google.appengine.api import images
from google.appengine.api.urlfetch import fetch
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from models import Dish
from operator import itemgetter, attrgetter
from user_info import UserFavDishes
import base64
import simplejson as json
import urllib2

class MatchDishes(webapp.RequestHandler):
    def get(self):
        self.response.out.write("In GET\n");
        
    def post(self):
        ingredients = self.request.get("ingredients")
        dishType = self.request.get("dishType")
        userId = self.request.get("userId")
        userHateIngsNames = self.request.get("hateIngs")
        userNeverShow = self.request.get("neverShow")
#        Call to getMatching dishes and send them to android
        self.getMatchingDishes(ingredients, dishType, userId, userHateIngsNames, userNeverShow)

    def getIngredients(self, ingredientString):
        ingredientNames = ingredientString.split(' ')
        result = []
        for ingName in ingredientNames:
            query = db.GqlQuery("SELECT __key__ FROM Ingredient WHERE name = :1 LIMIT 1", ingName.replace("_", " "))
            if query.count(1) != 0:
                result.append(query[0])
        return result
                 
         
         
    def getMatchingDishes(self, ingredientString, dishType, userId, userHateIngsNames, userNeverShow):
        ingredients = self.getIngredients(ingredientString)
        #This will be used instead when the key is sent correctly
        dishes = db.GqlQuery("SELECT * from Dish WHERE dishType = :1",db.Key(dishType)) #ADD IN QUERY DISH TYPE
        #dishes = db.GqlQuery("SELECT * from Dish")
        numMatching = 0 #To keep track of number of matching ingredients in every dish
        percMatch = 0 #To calculate the percentage of matching
        result = []
        numDishIngs = 0 #Number of ingredients in the dish currently inspected
        numSentIngs = len(ingredients)#Number of ingredients in the created dish sent from android
        for dish in dishes:
            if not UserFavDishes.doesHate(userId, dish.key(), userHateIngsNames, userNeverShow):
                numDishIngs = len(dish.ingredients)
                for ingredient in ingredients:
                    for dishIng in dish.ingredients:
                        if ingredient == dishIng:
                            numMatching = numMatching + 1
                if numMatching > 0:
                    #Take greater number of ingredients as base since it indicates the bigger difference
                    if numSentIngs > numDishIngs:
                        percMatch = round(((numMatching * 1.0) / numSentIngs) * 100)
                    else:
                        percMatch = round(((numMatching * 1.0) / numDishIngs) * 100)
                    if dish.img:
                        avatar = db.BlobProperty()
                        avatar = images.resize(dish.img, 150, 120)
                        result.append(dict(name=str(dish.name), percMatch=str(percMatch), img=base64.b64encode(avatar), key=str(dish.key())))
                    else:
                        result.append(dict(name=str(dish.name), percMatch=str(percMatch), key=str(dish.key())))
                numMatching = 0
        result.sort(key=itemgetter('percMatch'), reverse=True)
        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write(json.dumps(result))
application = webapp.WSGIApplication([('/match_dishes', MatchDishes)], debug=True)
  
def main():
    run_wsgi_app(application)
    
if __name__ == "__main__":
    main()
